package com.hzit.config;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.AfterRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 类名：
 * 作者：WF
 * 功能：自定义路由断言工厂
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
	public AgeRoutePredicateFactory() {
		super(Config.class);
	}
	// http://localhost:9000/student?age=20
	//1. 实现判断逻辑
	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return new Predicate<ServerWebExchange>() {
			@Override
			public boolean test(ServerWebExchange exchange) {
				ServerHttpRequest request = exchange.getRequest();
				String ageStr = request.getQueryParams().getFirst("age");   // 取出请求参数age的值
				int age = new Integer(ageStr);
				return age >= config.getMinAge() && age <= config.getMaxAge();
			}
		};
	}
	// 定义参数的顺序
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}
	// 定义参数类
	@Data
	public static class Config {
		private Integer minAge;
		private Integer maxAge;
	}
}
